package com.insight.mapper;

import com.insight.dto.datasource.DataSourceCreateRequest;
import com.insight.dto.datasource.DataSourceResponse;
import com.insight.dto.datasource.DataSourceUpdateRequest;
import com.insight.entity.DataSource;
import org.mapstruct.*;

import java.util.List;

/**
 * T033: DataSource MapStruct映射器
 * 自动生成实体与DTO之间的映射代码
 *
 * @author Insight Team
 */
@Mapper(componentModel = "spring",
        nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE,
        nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS)
public interface DataSourceMapper {

    /**
     * CreateRequest → Entity
     * 注意：密码加密应在Service层处理，此处不映射password字段
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "passwordEncrypted", ignore = true)
    @Mapping(target = "createdAt", ignore = true)
    @Mapping(target = "updatedAt", ignore = true)
    @Mapping(target = "createdBy", ignore = true)
    @Mapping(target = "updatedBy", ignore = true)
    DataSource toEntity(DataSourceCreateRequest request);

    /**
     * Entity → Response
     * 注意：不返回密码字段，添加数据库类型显示名称和JDBC URL
     */
    @Mapping(target = "dbTypeDisplayName", expression = "java(dataSource.getDbType().getDisplayName())")
    @Mapping(target = "jdbcUrl", expression = "java(dataSource.getDbType().buildJdbcUrl(dataSource.getHost(), dataSource.getPort(), dataSource.getDatabaseName()))")
    DataSourceResponse toResponse(DataSource dataSource);

    /**
     * Entity列表 → Response列表
     */
    List<DataSourceResponse> toResponseList(List<DataSource> dataSources);

    /**
     * UpdateRequest → Entity（仅更新非null字段）
     * 使用@MappingTarget更新现有实体
     */
    @Mapping(target = "id", ignore = true)
    @Mapping(target = "name", ignore = true)
    @Mapping(target = "dbType", ignore = true)
    @Mapping(target = "passwordEncrypted", ignore = true)
    @Mapping(target = "createdAt", ignore = true)
    @Mapping(target = "updatedAt", ignore = true)
    @Mapping(target = "createdBy", ignore = true)
    @Mapping(target = "updatedBy", ignore = true)
    @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
    void updateEntityFromRequest(DataSourceUpdateRequest request, @MappingTarget DataSource dataSource);
}
